import React from 'react'
import { Form, Input, Button, message, Card } from 'antd';
import { useNavigate, Navigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {fetchUserInfo } from '@/store/reducer/user'
import { getMenu } from '../../api'
import './index.css'

const Login = () => {
    const dispatch = useDispatch()
    // 进行创建页面跳转的路径
    const navigate = useNavigate()
    // 登录成功后进行主页面的鉴权
    if (localStorage.getItem('token')) {
        return <Navigate to='/LayoutPage/home' replace />
    }
    // 登录提交事件
    const handleSubmit = (val) => {
        console.log(val);
        if (!val.password || !val.username) {
            return message.open({
                type: 'warning',
                content: '请输入用户名和密码'
            })
        } else {
            // 代表登录成功之后能够成功获取到菜单数据
            getMenu(val).then(({ data }) => {
                localStorage.setItem('token', data.data.token)
                navigate('/LayoutPage/home')
                dispatch(fetchUserInfo(val))
            })
            return message.open({
                type: 'success',
                content: '登录成功'
            })
        }
    }



    return (
        <div className='login-right-content'>
            <Card>
                <div className='login-right-content-title'>
                    React组件后台管理系统
                </div>
                <div className='login-right-content-form'>
                    <Form
                        className="login-container"
                        onFinish={handleSubmit}
                        validateTrigger="onBlur"
                    >
                        <Form.Item
                            label="账号"
                            name="username"
                            // 执行顺序从上往下
                            rules={[{ required: true, message: '请输入账号' }, {
                                pattern:/^1[3-9]\d{9}$/,
                                message: '请输入正确的手机号'
                            }]}
                        >
                            <Input placeholder="请输入账号" />
                        </Form.Item>
                        <Form.Item
                            label="密码"
                            name="password"
                            rules={[{ required: true, message: '请输入密码' }]}
                        >
                            <Input.Password placeholder="请输入密码" />
                        </Form.Item>
                        <Form.Item className="login-button">
                            <Button type="primary" htmlType="submit">登录</Button>
                        </Form.Item>
                    </Form>
                </div>
            </Card>
        </div>
    )
}


export default Login
